package org.ruoyi.interview.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.ruoyi.interview.domain.InterviewQuestion;
import org.ruoyi.interview.mapper.InterviewQuestionMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.ai.chat.messages.UserMessage;
import org.springframework.ai.chat.prompt.Prompt;
import org.springframework.ai.ollama.OllamaChatClient;
import org.springframework.ai.ollama.api.OllamaOptions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * 面试题难度更新服务类
 * 通过Spring AI分析题目难度并更新数据库
 */
@Service
public class InterviewQuestionDifficultyUpdater {

    private static final Logger log = LoggerFactory.getLogger(InterviewQuestionDifficultyUpdater.class);

    @Autowired
    private InterviewQuestionMapper interviewQuestionMapper;

    @Autowired
    private OllamaChatClient ollamaChatClient;

    @Value("${spring.ai.ollama.base-url:http://localhost:11434}")
    private String ollamaBaseUrl;

    @Value("${spring.ai.ollama.chat.options.model:qwen2.5:7b}")
    private String modelName;

    /**
     * 更新所有面试题的难度等级
     */
    public void updateAllQuestionDifficulties() {
        QueryWrapper<InterviewQuestion> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("difficulty", "");
        List<InterviewQuestion> questions = interviewQuestionMapper.selectList(queryWrapper);

        log.info("开始更新面试题的难度等级");

        for (InterviewQuestion question : questions) {
            try {
                // 跳过已经有难度等级的题目
                if (question.getDifficulty() != null && !question.getDifficulty().isEmpty()) {
                    continue;
                }

                String difficulty = analyzeQuestionDifficulty(question.getContent());
                question.setDifficulty(difficulty);
                interviewQuestionMapper.updateById(question);
                log.info("已更新题目ID {} 的难度等级为: {}", question.getQuestionId(), difficulty);

                // 添加延迟以避免过于频繁的请求
                Thread.sleep(1000);
            } catch (Exception e) {
                log.error("更新题目ID {} 的难度等级时出错: {}", question.getQuestionId(), e.getMessage());
            }
        }

        log.info("面试题难度等级更新完成");
    }

    /**
     * 分析单个面试题的难度等级
     *
     * @param questionContent 题目内容
     * @return 难度等级 (简单、中等、困难)
     */
    public String analyzeQuestionDifficulty(String questionContent) {
        // 改进提示词设计，更明确地指导模型输出
        String promptText = "请分析以下面试题的难度等级，必须且只能从以下三个选项中选择一个：简单、中等、困难\n\n面试题："
            + questionContent + "\n\n请只回答“简单”、“中等”或“困难”中的一个词，不要包含其他内容。";

        log.info("正在分析题目难度: {}", promptText);

        Prompt prompt = new Prompt(
            new UserMessage(promptText),
            OllamaOptions.create().withModel(modelName).withTemperature(0.2f)
        );

        try {
            String response = ollamaChatClient.call(prompt).getResult().getOutput().getContent();
            String difficulty = response.trim();

            // 增加结果验证和清理逻辑
            // 提取可能包含在其他文本中的有效结果
            if (difficulty.contains("简单")) {
                return "简单";
            } else if (difficulty.contains("中等")) {
                return "中等";
            } else if (difficulty.contains("困难")) {
                return "困难";
            }

            // 如果没有匹配到有效结果，记录详细日志
            log.warn("模型返回了非预期的结果: {}", difficulty);
            return "未知"; // 或者抛出异常

        } catch (Exception e) {
            log.error("调用模型分析题目难度时出错: ", e);
            return "未知";
        }
    }


    /**
     * 验证难度等级是否有效
     *
     * @param difficulty 难度等级
     * @return 是否有效
     */
    private boolean isValidDifficulty(String difficulty) {
        return "简单".equals(difficulty) || "中等".equals(difficulty) || "困难".equals(difficulty);
    }
}
